package com.tanhua.dubbo.api.db;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.api.mapper.UserInfoMapper;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息服务接口实现类
 */
@DubboService
public class UserInfoApiImpl implements UserInfoApi{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void add(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo getById(Long userId) {
        return userInfoMapper.selectById(userId);
    }

    @Override
    public List<UserInfo> getBatchIds(List<Long> ids) {
        return userInfoMapper.selectBatchIds(ids);
    }

    /**
     * 根据ids和条件查询用户列表
     * @Param ids
     * @param userInfoCondition
     * @return
     */
    @Override
    public Map<Long, UserInfo> getBatchIdsByCondition(List<Long> ids, UserInfo userInfoCondition) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserInfo::getId, ids);
        if(null != userInfoCondition) {
            queryWrapper.le(null != userInfoCondition.getAge(), UserInfo::getAge, userInfoCondition.getAge())
                    .eq(null != userInfoCondition.getGender(), UserInfo::getGender, userInfoCondition.getGender())
                    .eq(null != userInfoCondition.getCity(), UserInfo::getCity, userInfoCondition.getCity())
                    .eq(null != userInfoCondition.getEducation(), UserInfo::getEducation, userInfoCondition.getEducation())
                    .like(null != userInfoCondition.getNickname(), UserInfo::getNickname, userInfoCondition.getNickname());
        }
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);

        Map<Long, UserInfo> map = new HashMap<>();
        userInfos.forEach(userInfo -> {
            map.put(userInfo.getId(), userInfo);
        });
        return map;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<UserInfo> findPage(Long page, Long pageSize) {
        IPage<UserInfo> iPage = new Page<>(page, pageSize);
        userInfoMapper.selectPage(iPage, null);
        return new PageResult<>(page, pageSize, iPage.getTotal(), iPage.getRecords());
    }
}
